package com.open.source;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author page-view
 * <p>des</p>
 **/
@Configuration
@Component
public class DynamicDataSourceConfig {

    public static final Map<String,String> systemMap = new HashMap<>();

    public Map<String,String> getSystemMap(){
        // 如果是Linux端 则使用prod数据源
        systemMap.put("linux","prod");
        // 如果是Windows端 则使用local数据源
        systemMap.put("windows","local");
        return systemMap;
    }

    public DataSource getDataSource(Map<Object, Object> targetDataSources,DataSource localDataSource, DataSource prodDataSource){
        String sysName = System.getProperty("os.name").toLowerCase();
        for (Map.Entry<String, String> entry : getSystemMap().entrySet()) {
            if (sysName.contains(entry.getKey().toLowerCase())){
                switch (entry.getKey()){
                    case "linux":
                        targetDataSources.put(entry.getValue(),prodDataSource);
                        return prodDataSource;
                    case "windows":
                        targetDataSources.put(entry.getValue(),localDataSource);
                        return localDataSource;
                }
            }
        }
        return null;
    }


    @Bean
    @ConfigurationProperties("spring.datasource.druid.local")
    public DataSource localDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.prod")
    public DataSource prodDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource localDataSource, DataSource prodDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        DataSource dataSource = getDataSource(targetDataSources, localDataSource, prodDataSource);
        if (dataSource != null) {
            return new DynamicDataSource(dataSource, targetDataSources);
        }
        /**
         *
         */
        return new DynamicDataSource(localDataSource, targetDataSources);
    }
}